home *** CD-ROM | disk | FTP | other *** search
- Path: news.th-darmstadt.de!news
- From: Enno Sandner <enno@intellektik.informatik.th-darmstadt.de>
- Newsgroups: comp.lang.c++
- Subject: Re: Deleting Data Members that are Const Pointers / References?
- Date: Mon, 26 Feb 1996 15:41:16 +0100
- Organization: Fachbereich Informatik, TH Darmstadt
- Message-ID: <3131C68C.446B9B3D@intellektik.informatik.th-darmstadt.de>
- References: <4groo7$4bt@radmail.rad.co.il>
- NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (X11; I; SunOS 4.1.3 sun4m)
-
- udi wrote:
- >
- > news:comp.lang.c++#pvcybpuqx6p.fsf@hln56.pki-nbg.philips.de
- >
- > Hi everybody,
- >
- > I have a simple question regarding data members that are
- > constant pointers or references.
- > Let's say I have a class Foo that has a data member xr (say of type int&
- > - in reality a different type) that is a constant reference. Objects of
- > class Foo must have an instance of xr during their lifetime, that's a
- > reason to have xr a reference. Also, xr must not change (not even
- > accidentaly, by some member function / friend of Foo), that's why I want
- > xr to be constant.Foo is always initialized with an int that was
- > allocated off the heap, but xr should cease to exist when Foo does, so
- > Foo is responsible to destroy xr and free the memory occupied by it.
- > However, deleting a const reference (pointer) is not allowed (at least
- > according to Borland 4.5 and g++). This seems logical as the operand to
- > delete is a void* and the compiler says he can't convert a const int* to
- > a void*.
- > So, THE QUESTION IS:
- > Is there an alternative to brutally casting the const away?
- >
- > A sample code:
- >
- > class Foo [
- > public:
- > Foo(const int& xr1) : xr(xr1) {}
- > ~Foo() [ delete &xr; ] // ERROR - attempt to delete a constant pointer
- > private:
- > int& xr;
- > ];
- >
- > int main() {
- > int& xr1 = *(new int(100));
- > Foo* fooP = new Foo(xr1);
- > //...
- > delete fooP;
- > }
- >
- > Alternative:
- > ~Foo() [ delete (int*)(&xr); ] // BRUTAL CASTING
- >
-
- The casting hack works but is no longer necessary.
- According to the DWP you can delete a 'const'-object.
- Check out for a newer version of 'g++'. For instance
- g++ 2.7.2 doesn't complain about deleting a const-object.
-
- Enno
-